
# ==========================================================================#
#                              TCP服务器监听线程
# 功能：监听客户端连接
#      创建客户端通信线程
#      关闭客户端通信线程
#      清除客户端连接列表等
# ==========================================================================#
from PyQt5.QtCore import QThread

from recv_send import Thread_Recv_Send
from Robotics import Robot

import global_var

class Server_Thread(QThread):
    def __init__(self, serverSocket, data_signal):
        super().__init__()

        print('2.TCP服务器线程接收到socket')

        self.run_flag = True
        self.data_signal = data_signal
        self.serverSocket = serverSocket
        # self.close_server_signal.connect(self.close_server)

    def run(self):
        print('3.等待客户端连接......')
        while True:
            # ================ 监听客户端连接 ================#
            # 收到客户端的连接后返回 连接控件,地址(持续监听,直到接收到执行下一个操作)
            self.clientsocket, self.addr = self.serverSocket.accept()
            # 连接数加一
            global_var.set_client_num(global_var.get_client_num() + 1)
            global_var.set_connect_change(True)
            print('接受第', global_var.get_client_num(), '个新客户端连接:', self.addr)
            # 添加客户端addr
            global_var.append_client_addrs(self.addr[1])
            # 添加clientsocket
            global_var.append_clientsockets(self.clientsocket)
            # 添加Robot对象
            global_var.append_Robot_list(Robot())
            # 创建新的客户端通信子线程，传入clientsocket、addr、断开连接信号
            self.thread_recv_send = Thread_Recv_Send(self.clientsocket, self.addr[1], self.data_signal)
            self.thread_recv_send.start()
            global_var.append_Thread_recv_send_list(self.thread_recv_send)
